package com.app.micaihu.view.main;

import android.app.LauncherActivity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationManagerCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.Observer;
import androidx.viewpager.widget.ViewPager;

import com.android.volley.VolleyError;
import com.app.base.BaseActivity;
import com.app.micaihu.R;
import com.app.micaihu.adapter.MainFragmentTabAdapter;
import com.app.micaihu.app.AppApplication;
import com.app.micaihu.base.bean.DataBean;
import com.app.micaihu.bean.ad.NativeAd;
import com.app.micaihu.bean.message.MsgCenter;
import com.app.micaihu.bean.message.MsgHonourRed;
import com.app.micaihu.bean.message.MsgRed;
import com.app.micaihu.configure.AppConfigTools;
import com.app.micaihu.configure.Config;
import com.app.micaihu.configure.ConfigKeyConstant;
import com.app.micaihu.configure.URIContant;
import com.app.micaihu.configure.UmEventId;
import com.app.micaihu.custom.components.NoDoubleClickListener;
import com.app.micaihu.custom.components.ParamMap;
import com.app.micaihu.listener.HttpListener;
import com.app.micaihu.manager.AppConfigManager;
import com.app.micaihu.manager.IPushManager;
import com.app.micaihu.manager.ServiceDeliveryManager;
import com.app.micaihu.manager.UserInforManager;
import com.app.micaihu.utils.CheckVersionUtils;
import com.app.micaihu.utils.DialogUtils;
import com.app.micaihu.utils.HttpUtils;
import com.app.micaihu.utils.InteractiveUtils;
import com.app.micaihu.utils.MobclickAgentUtils;
import com.app.micaihu.utils.MutileThreadDownload;
import com.app.micaihu.videoplayer.JCVideoPlayer;
import com.app.micaihu.view.home.arms.fragment.ArmsListFragment;
import com.app.micaihu.view.lunch.LunchActivity;
import com.app.micaihu.view.main.dialog.MainAgreeDialogFragment;
import com.app.micaihu.view.main.dialog.MainLoginDialogFragment;
import com.app.micaihu.view.main.dialog.MainNoLoginDialogFragment;
import com.app.micaihu.view.main.dialog.NetChangeDialog;
import com.app.micaihu.view.main.fragment.HomeFragment;
import com.app.micaihu.view.main.fragment.LegionFragment;
import com.app.micaihu.view.main.mine.fragment.MineFragment;
import com.app.micaihu.view.main.msgcenter.fragment.MessageFragment;
import com.app.micaihu.view.main.topic.PostSendActivity;
import com.app.micaihu.view.utils.DownloadAgainUtils;
import com.app.utils.biz.Biz;
import com.app.utils.util.DateUtils;
import com.app.utils.util.StringUtils;
import com.app.utils.util.ToastUtils;
import com.app.utils.util.osutils.StatusBarUtils;
import com.baidu.mobstat.StatService;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.CollectionUtils;
import com.blankj.utilcode.util.ColorUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ViewUtils;
import com.google.gson.reflect.TypeToken;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.next.easynavigation.view.EasyNavigationBar;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;


/**
 * 主页面
 * Created by linkai on 2016/7/13.
 */
public class MainActivity extends BaseActivity {

    private String mPageName = "MainActivity";//当前的网络请求标识
    /************
     * 页面控件oncl
     ******************/
    private EasyNavigationBar easyNavigationBar;
    private HomeFragment mHomeFragment;//主页Fragment
    private LegionFragment legionFragment;//军团Fragment
    private ArmsListFragment armsListFragment;
    private MessageFragment mMessageFragment;//消息Fragment
    private MineFragment mMineFragment;//我的Fragment
    private MainFragmentTabAdapter tabAdapter;// 管理主页面fragment的管理者
    private long mExitTime;//最后一次点击的时间

    private boolean isShowMenu; //是否显示 首页

    private NetChangeDialog netChangeDialog;

    private NetworkUtils.OnNetworkStatusChangedListener networkStatusChangedListener = new NetworkUtils.OnNetworkStatusChangedListener() {
        @Override
        public void onDisconnected() {
        }

        @Override
        public void onConnected(NetworkUtils.NetworkType networkType) {
            if (networkType == null) return;
            switch (networkType) {
                case NETWORK_2G:
                case NETWORK_3G:
                case NETWORK_4G:
                case NETWORK_5G:
                    ViewUtils.runOnUiThreadDelayed(new Runnable() {
                        @Override
                        public void run() {
                            int downLoadSize = DownloadAgainUtils.pauseDownLoadGame();
                            if (downLoadSize > 0) {
                                netChangeDialog = new NetChangeDialog();
                                Bundle bundle = new Bundle();
                                bundle.putInt(Config.Extra.max, downLoadSize);
                                netChangeDialog.setArguments(bundle);
                                netChangeDialog.show((FragmentActivity) ActivityUtils.getTopActivity());
                            }
                        }
                    }, 1000);
                    break;
                case NETWORK_WIFI:
                    if (AppApplication.isOpenApp) {
                        DownloadAgainUtils.downLoadGame();
                    }
                    break;
            }
        }
    };

    @Override
    protected void initBar(boolean initBar) {
        super.initBar(false);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void setData() {
        NetworkUtils.registerNetworkStatusChangedListener(networkStatusChangedListener);

        StatusBarUtils.setStatusBar(this);
        isShowMenu = SPUtils.getInstance().getBoolean(ConfigKeyConstant.indexButtonSwitch, true);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            // 适配7.0 相机
            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());
            builder.detectFileUriExposure();
        }
        //如果MainActivity创建了.那么就finish掉LunchActivity
        if (ActivityUtils.isActivityExistsInStack(LauncherActivity.class)) {
            ActivityUtils.finishActivity(LunchActivity.class);
        }

        //友盟推送,与统计无关,作为日活统计,可以分条件来推送
        if (AppConfigManager.getInstance().readConfig(ConfigKeyConstant.option_isPull, true)) {

        }
        startLogic();
        ServiceDeliveryManager.getSingleton().dealActivityQueue(tabAdapter);
        boolean isFirstShowAgreement = SPUtils.getInstance().getBoolean(ConfigKeyConstant.isFirstShowAgreement, true);
        boolean forceLogin = SPUtils.getInstance().getBoolean(ConfigKeyConstant.forceLogin, false);
        if (isFirstShowAgreement) {
            showAgreeDialog();
        } else {
            if (forceLogin && com.blankj.utilcode.util.StringUtils.isEmpty(Biz.getInstance().uid())) {
                UserInforManager.getInstance().toLoginPage(this);
            } else {
                showLoginDialog();
            }
        }
    }

    private boolean isNotificationEnabled(Context context) {
        boolean isOpened = false;
        try {
            isOpened = NotificationManagerCompat.from(context).areNotificationsEnabled();
        } catch (Exception e) {
            e.printStackTrace();
            isOpened = false;
        }
        return isOpened;
    }

    private void gotoNotificationEnabledSet() {
        Intent intent = new Intent();
        if (Build.VERSION.SDK_INT >= 26) {
            // android 8.0引导
            intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
            intent.putExtra("android.provider.extra.APP_PACKAGE", getPackageName());
        } else if (Build.VERSION.SDK_INT >= 21) {
            // android 5.0-7.0
            intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
            intent.putExtra("app_package", getPackageName());
            intent.putExtra("app_uid", getApplicationInfo().uid);
        } else {
            // 其他
            intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            intent.setData(Uri.fromParts("package", getPackageName(), null));
        }
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);

    }

    @Override
    protected void addListeners() {
        LiveEventBus.get(Config.EventBus.loginSuccess, Boolean.class).observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(@Nullable Boolean loginSuccess) {
                if (loginSuccess != null && loginSuccess) {
                    ViewUtils.runOnUiThreadDelayed(() -> {
                        String currentTime = DateUtils.getCurrentTime(DateUtils.formatDefault);
                        String isShowLoginDialogData = SPUtils.getInstance().getString(ConfigKeyConstant.isShowLoginDialogData);
                        if (currentTime.equals(isShowLoginDialogData)) return;
                        MainLoginDialogFragment mainLoginDialog = new MainLoginDialogFragment();
                        mainLoginDialog.show(getSupportFragmentManager());
                    }, 500);
                }
            }
        });
        LiveEventBus.get(Config.EventBus.flushMsgRed, Integer.class).observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(@Nullable Integer flushMsgRed) {
                if (flushMsgRed != null) {
                    changeMessageCount(flushMsgRed);
                }
            }
        });
        LiveEventBus.get(Config.EventBus.goHome, Boolean.class).observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(@Nullable Boolean goHome) {
                if (goHome != null && goHome) {
                    easyNavigationBar.selectTab(0, true);
                }
            }
        });
        LiveEventBus.get(Config.EventBus.goArmy, Boolean.class).observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(@Nullable Boolean goArmy) {
                if (goArmy != null && goArmy) {
                    if (isShowMenu) {
                        easyNavigationBar.selectTab(1, true);
                    } else {
                        easyNavigationBar.selectTab(0, true);
                    }
                }
            }
        });
    }

    private void showLoginDialog() {
        String currentTime = DateUtils.getCurrentTime(DateUtils.formatDefault);
        String isShowLoginDialogData = SPUtils.getInstance().getString(ConfigKeyConstant.isShowLoginDialogData);
        if (currentTime.equals(isShowLoginDialogData)) {
            DownloadAgainUtils.showDownLoadDialog(getSupportFragmentManager());
            return;
        }

        boolean login = UserInforManager.getInstance().isLogin();
        if (login) {
            MainLoginDialogFragment mainLoginDialog = new MainLoginDialogFragment();
            mainLoginDialog.show(getSupportFragmentManager());
        } else {
            String isShowNoLoginDialogData = SPUtils.getInstance().getString(ConfigKeyConstant.isShowNoLoginDialogData);
            if (currentTime.equals(isShowNoLoginDialogData)) {
                DownloadAgainUtils.showDownLoadDialog(getSupportFragmentManager());
                return;
            }
            MainNoLoginDialogFragment mainNoLoginDialog = new MainNoLoginDialogFragment();
            mainNoLoginDialog.show(getSupportFragmentManager());
        }
    }

    private void showAgreeDialog() {
        MainAgreeDialogFragment.newInstance().show(getSupportFragmentManager());
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        flushMsgDotSum();
    }

    @Override
    protected void onResume() {
        super.onResume();
        flushMsgDotSum();
    }

    @Override
    protected void onStop() {
        super.onStop();
        //释放播放器资源
        JCVideoPlayer.releaseAllVideos();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);//反注册EventBus
        InteractiveUtils.getInstance().saveLaudList();
        NetworkUtils.unregisterNetworkStatusChangedListener(networkStatusChangedListener);
    }

    /**
     * 启动逻辑程序
     */
    private void startLogic() {
        easyNavigationBar = findViewById(R.id.navigationBar);
        initFragments();//初始化需要展示的页面录
        UserInforManager.getInstance().localWeiLogin(this);//伪登
        new CheckVersionUtils().checkVertion(this, false);//检查版本更新
        EventBus.getDefault().register(this);
        checkPushPrompt();//检查push红点
        initLaudAndDefriendList();//初始化点赞列表
    }


    /**
     * 初始化点赞列表
     */
    private void initLaudAndDefriendList() {

        if (InteractiveUtils.getInstance().getCurrentLaudList() == null || !UserInforManager.getInstance().isLogin()) {
            new Thread() {
                @Override
                public void run() {
                    InteractiveUtils.getInstance().readLaudFromLocal();
                }
            }.start();
        }
    }


    /**
     * 提示推送的dialog
     */
    private void checkPushPrompt() {

        long lastShowTime = AppConfigManager.getInstance().readConfig(ConfigKeyConstant.push_dialog_show_time, 0L);
        boolean isPush = AppConfigManager.getInstance().readConfig(ConfigKeyConstant.option_isPull, true);
        if (!isPush && lastShowTime == 0
                || !isPush && lastShowTime != 0 && System.currentTimeMillis() - lastShowTime > AppConfigTools.PUSHPROMPT_DIALOG_SHOW_INTERVAL) {
            View pushDialogView = LayoutInflater.from(this).inflate(R.layout.dialog_push_prompt, null);
            ImageView cancel = (ImageView) pushDialogView.findViewById(R.id.iv_cancle);
            TextView yes = (TextView) pushDialogView.findViewById(R.id.tv_btn);
            cancel.setOnClickListener(onclick);
            yes.setOnClickListener(onclick);
            HashMap<String, Object> dialogParams = new HashMap<>();
            dialogParams.put("width", 300);
            DialogUtils.getInstance().showCDialog(pushDialogView, this, dialogParams);
            AppConfigManager.getInstance().writeConfig(ConfigKeyConstant.push_dialog_show_time, System.currentTimeMillis());
        }

    }

    /**
     * 加载需要显示的内容
     */
    private void initFragments() {
        ArrayList<Fragment> fragments = new ArrayList<>();
        String[] tabText;
        int[] normalIcon;
        int[] selectIcon;
        if (isShowMenu) {
            this.mHomeFragment = new HomeFragment();
            fragments.add(this.mHomeFragment);
            tabText = new String[]{"首页", "话题", "武器库", "消息", "我"};
            //未选中icon
            normalIcon = new int[]{R.drawable.tabbar_infor_nor,
                    R.drawable.tabbar_topic_nor,
                    R.drawable.tabbar_ranking_nor,
                    R.drawable.tabbar_news_nor,
                    R.drawable.tabbar_my_nor};
            //选中时icon
            selectIcon = new int[]{R.drawable.tabbar_infor_sel,
                    R.drawable.tabbar_topic_sel,
                    R.drawable.tabbar_ranking_sel,
                    R.drawable.tabbar_news_sel,
                    R.drawable.tabbar_my_sel};

        } else {
            tabText = new String[]{"话题", "武器库", "消息", "我"};
            //未选中icon
            normalIcon = new int[]{
                    R.drawable.tabbar_topic_nor,
                    R.drawable.tabbar_ranking_nor,
                    R.drawable.tabbar_news_nor,
                    R.drawable.tabbar_my_nor};
            //选中时icon
            selectIcon = new int[]{
                    R.drawable.tabbar_topic_sel,
                    R.drawable.tabbar_ranking_sel,
                    R.drawable.tabbar_news_sel,
                    R.drawable.tabbar_my_sel};
        }

        this.legionFragment = new LegionFragment();
        fragments.add(this.legionFragment);

        this.armsListFragment = new ArmsListFragment();
        fragments.add(this.armsListFragment);

        this.mMessageFragment = new MessageFragment();
        fragments.add(this.mMessageFragment);

        this.mMineFragment = new MineFragment();
        fragments.add(this.mMineFragment);

        easyNavigationBar.titleItems(tabText)
                .normalIconItems(normalIcon)
                .selectIconItems(selectIcon)
                .fragmentList(fragments)
                .normalTextColor(ColorUtils.getColor(R.color.main_bottom_menu))
                .selectTextColor(ColorUtils.getColor(R.color.app_theme))
                .tabTextSize(10)
//                .anim(Anim.Pulse)
                .navigationHeight(45) //导航栏高度
                .iconSize(20) //Tab图标大小
                .canScroll(false)
                .smoothScroll(true)
                .lineColor(ColorUtils.getColor(R.color.common_underline))
                .lineHeight(1)
                .fragmentManager(getSupportFragmentManager())
                .build();
        ViewPager viewPager = easyNavigationBar.getViewPager();
        if (viewPager != null) {
            viewPager.setOffscreenPageLimit(fragments.size());
        }
        easyNavigationBar.setOnTabClickListener(new EasyNavigationBar.OnTabClickListener() {
            @Override
            public boolean onTabSelectEvent(View view, int position) {
                if (isShowMenu) {
                    if (position == 2 && com.blankj.utilcode.util.StringUtils.isEmpty(Biz.getInstance().uid())) {
                        UserInforManager.getInstance().toLoginPage(getThisActivity());
                        return true;
                    }
                    if (position > 0) {
                        if (mHomeFragment != null) {
                            mHomeFragment.onDataRefreshingEnd();
                            mHomeFragment.resetFlushViewBg();
                        }
                    }
                } else {
                    if (position == 1 && com.blankj.utilcode.util.StringUtils.isEmpty(Biz.getInstance().uid())) {
                        UserInforManager.getInstance().toLoginPage(getThisActivity());
                        return true;
                    }
                }

                HashMap<String, Object> map = new HashMap<>();
                if (isShowMenu) {
                    if (position == 0) {
                        map = UmEventId.INSTANCE.getBotnav_mainbutton();
                    } else if (position == 1) {
                        map = UmEventId.INSTANCE.getBotnav_communitybutton();
                    } else if (position == 2) {
                        map = UmEventId.INSTANCE.getBotnav_tool();
                    } else if (position == 3) {
                        map = UmEventId.INSTANCE.getBotnav_news();
                    } else if (position == 4) {
                        map = UmEventId.INSTANCE.getBotnav_mine();
                    }
                } else {
                    if (position == 0) {
                        map = UmEventId.INSTANCE.getBotnav_communitybutton();
                    } else if (position == 1) {
                        map = UmEventId.INSTANCE.getBotnav_tool();
                    } else if (position == 2) {
                        map = UmEventId.INSTANCE.getBotnav_news();
                    } else if (position == 3) {
                        map = UmEventId.INSTANCE.getBotnav_mine();
                    }
                }
                MobclickAgentUtils.event(UmEventId.nav_button, map);
                return false;
            }

            @Override
            public boolean onTabReSelectEvent(View view, int position) {//重复点击
                List<ImageView> tabList = easyNavigationBar.getTabList();
                if (CollectionUtils.isNotEmpty(tabList)) {
                    if (CollectionUtils.isNotEmpty(tabList)) {
                        if (isShowMenu && position == 0) {
                            JCVideoPlayer.releaseAllVideos();
                            if (mHomeFragment != null) {
                                mHomeFragment.flushCurrentPage(tabList.get(0));
                            }
                        }
                    }
                }
                return false;
            }
        });
    }

    private void flushMsgDotSum() {
        flushMsg();
        flushMyHonour();
        //视频的小红点
//        flushVideo();
//        flushMineRed();
    }

    /**
     * 刷新 视频红点
     */
    private void flushVideo() {
        final Map<String, String> redParam = new HashMap<>();
        if (UserInforManager.getInstance().isLogin()) {
            redParam.put("uid", UserInforManager.getInstance().getUserInfor().getUid());
        } else {
            redParam.put("uid", "0");
        }
        HttpListener<DataBean<MsgRed>> msgRedListener = new HttpListener<DataBean<MsgRed>>() {
            @Override
            public void onError(VolleyError error) {
            }

            @Override
            public void onSuccess(DataBean<MsgRed> response) {
                if (response.noError() && response.getData() != null) {
                    String latestOriginTime = response.getData().getLatestOriginTime();
                    if (!TextUtils.isEmpty(latestOriginTime)) {
                        long localTime = AppConfigManager.getInstance().readConfig(ConfigKeyConstant.video_updata_time, 0L);
                        long aLong = StringUtils.toLong(latestOriginTime, 0L);
                        if (aLong * 1000 - localTime > 0) {
//                            videoRedDot.setVisibility(View.VISIBLE);
                        }
                    }
                }
            }
        };
        HttpUtils.addPostCacheRequest(URIContant.MSG_REDDOT,
                new TypeToken<DataBean<MsgRed>>() {
                }.getType(), this.mPageName, redParam, msgRedListener);
    }

    /**
     * 刷新消息红点
     */
    private void flushMyHonour() {
        Map<String, String> params = new HashMap<>();
        if (com.blankj.utilcode.util.StringUtils.isEmpty(Biz.getInstance().uid())) {
            params.put("uid", "0");//未登录状态下，传0 or ""，服务器返回不带num的列表数据
        } else {
            params.put("uid", Biz.getInstance().uid());
        }

        final HttpListener<DataBean<MsgHonourRed>> msgCenter = new HttpListener<DataBean<MsgHonourRed>>() {

            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onError(VolleyError error) {

            }

            @Override
            public void onSuccess(DataBean<MsgHonourRed> response) {
                if (response.noError()) {
                    MsgHonourRed data = response.getData();
                    if (data != null) {
                        boolean status = data.isStatus();
                        if (isShowMenu) {
                            easyNavigationBar.setHintPoint(4, status);
                        } else {
                            easyNavigationBar.setHintPoint(3, status);
                        }
                        if (mMineFragment != null) {
                            mMineFragment.setHonourMsg(status);
                        }
                    }
                }
            }
        };
        HttpUtils.addPostCacheRequest(URIContant.MESSAGE_MEDAL, new TypeToken<DataBean<MsgHonourRed>>() {
        }.getType(), this.mPageName, params, msgCenter);
    }

    /**
     * 刷新消息红点
     */
    private void flushMsg() {
        Map<String, String> params = new HashMap<>();
        if (com.blankj.utilcode.util.StringUtils.isEmpty(Biz.getInstance().uid())) {
            params.put("uid", "0");//未登录状态下，传0 or ""，服务器返回不带num的列表数据
        } else {
            params.put("uid", Biz.getInstance().uid());
        }

        final HttpListener<DataBean<ArrayList<MsgCenter>>> msgCenter = new HttpListener<DataBean<ArrayList<MsgCenter>>>() {

            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onError(VolleyError error) {
            }

            @Override
            public void onSuccess(DataBean<ArrayList<MsgCenter>> response) {
                if (response.noError()) {
                    msgList = response.getData();
                    if (msgList != null && !msgList.isEmpty()) {
                        int msgNum = 0;
                        for (int i = 0; i < msgList.size(); i++) {
                            if (msgList.get(i) != null) {
                                msgNum += StringUtils.toInt(msgList.get(i).getNum(), 0);
                            }
                        }
                        changeMessageCount(msgNum);
                    }
                }
            }
        };
        HttpUtils.addPostCacheRequest(URIContant.MESSAGE_CENTER, new TypeToken<DataBean<ArrayList<MsgCenter>>>() {
        }.getType(), this.mPageName, params, msgCenter);
    }

    List<MsgCenter> msgList;
    /**
     * 所有控件的点击事件
     *
     * @param v
     */
    NoDoubleClickListener onclick = new NoDoubleClickListener() {
        @Override
        public void onNoDoubleClick(View v) {
            if (v == null) {
                return;
            }
            switch (v.getId()) {
                case R.id.iv_cancle:
                    DialogUtils.getInstance().dismissCDialog();
                    break;
                case R.id.tv_btn:
                    DialogUtils.getInstance().dismissCDialog();
                    IPushManager.getInstance().startPush();
                    AppConfigManager.getInstance().writeConfig(ConfigKeyConstant.option_isPull, true);
                    break;

            }
        }
    };

    /**
     * 发帖操作
     */
    private void sendPostOpration() {

        if (UserInforManager.getInstance().isLogin()) {
            Intent intent = new Intent(this, PostSendActivity.class);
            intent.putExtra("tansImg", UserInforManager.getInstance().getUserInfor().getTansImg());
//            startActivityForResult(intent, BaseActivity.REQUESTCODE_1);
            startActivity(intent);
            overridePendingTransition(R.anim.translate_slide_in_bottom, R.anim.slide_out_left);
            StatService.onEvent(this, "063", "跳转发帖页面", 1);// 统计的点击
        } else {
            UserInforManager.getInstance().toLoginPage(this);
        }
    }

    /**
     * 刷新消息
     */
    private void flushMessage() {
        if (mMessageFragment != null) {
            mMessageFragment.flushData();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event == null)
            return true;// 防止nullException
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (JCVideoPlayer.backPress()) {
                //判断是否有视频全屏
                return true;
            }
            //如果连续点击的时间大于2秒
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                try {
                    ToastUtils.showText("再按一次退出");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                mExitTime = System.currentTimeMillis();
            } else {
                ActivityUtils.finishAllActivities();
            }
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_MENU) {
            // 拦截MENU按钮点击事件，让他无任何操作
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void startActivity(Intent intent) {
        super.startActivity(intent);
        overridePendingTransition(R.anim.base_slide_right_in, R.anim.base_slide_remain);
    }

    /**
     * 获取当前选中的页面下标
     *
     * @return
     */
    public int getMainFragmentCurrent() {
        if (tabAdapter != null) {
            return tabAdapter.getCurrentTab();
        }
        return -1;
    }


    /**
     * 别的界面操作主界面的事件
     *
     * @param parms
     */
    public static final String FLUSH_MINE_RED = "10";

    public void onEventMainThread(ArrayList<Object> parms) {
        if (parms == null || parms.size() == 0) return;
        String type = parms.get(0).toString();
        if (TextUtils.isEmpty(type)) {
            return;
        }

        switch (type) {
//            case TypeConstant.HANDLER_TYPE_1://切换阅读模式
//                boolean b = (boolean) parms.get(1);
//                tooleReadMode(b);
//                break;
//            case "7"://展示帖子界面
//                showGuide(R.id.iv_guide_post);
//                break;
//            case "2"://展示搜索引导
//                showGuide(R.id.iv_guide_search);//展示搜索引导
//                break;
//            case "3"://展示军功浮层
//                showGuide(R.id.iv_guide_jungong);
//                break;
            case "4"://修改消息总数
                int mesgNum = 0;
                try {
                    mesgNum = StringUtils.toInt(parms.get(1).toString(), 0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                changeMessageCount(mesgNum);
                break;
            case "5"://刷新消息
                flushMessage();
                break;
            case "6"://隐藏右上角小红点
//                if (mRedDot != null) {
//                    mRedDot.setVisibility(View.GONE);
//                }
                break;

            case "8"://显示 游戏 浮层
//                showGuide(R.id.iv_guide_2);
                break;
            case "9"://显示游戏下载管理  浮层
//                showGuide(R.id.iv_guide_downmanager);
                break;
            case FLUSH_MINE_RED://显示游戏下载管理  浮层
//                flushMineRed();
                break;

        }
    }


    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            JCVideoPlayer.IS_FULLSCREEN = true;
        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            JCVideoPlayer.IS_FULLSCREEN = false;
        }
    }

    /**
     * 修改消息
     *
     * @param msgRed
     */
    public void changeMessageCount(int msgRed) {
        if (isShowMenu) {
            easyNavigationBar.setMsgPointCount(3, msgRed);
        } else {
            easyNavigationBar.setMsgPointCount(2, msgRed);
        }
    }


    public interface OnRefreshingListener {
        void onDataRefreshingStart();

        void onDataRefreshingEnd();
    }

    private void initGameDialog() {
        ParamMap parms = new ParamMap();
        HttpListener<DataBean<NativeAd>> httpListener = new HttpListener<DataBean<NativeAd>>() {
            @Override
            public void onError(VolleyError error) {

            }

            @Override
            public void onSuccess(DataBean<NativeAd> response) {
                if (response.noErrorData()) {
                    NativeAd nativeAd = response.getData();
                    if (TextUtils.isEmpty(nativeAd.getJumpUrl())) {
                        return;
                    }
                    if (nativeAd.getThumbList() != null && nativeAd.getThumbList().length > 0) {
                        new MutileThreadDownload(MainActivity.this).startDown(nativeAd.getJumpUrl(), nativeAd.getTitle(),
                                nativeAd.getPackageName(), nativeAd.getThumbList()[0], nativeAd.getPromoteUrl()
                                , nativeAd.getStyle());
                    } else {
                        new MutileThreadDownload(MainActivity.this).startDown(nativeAd.getJumpUrl(), nativeAd.getPackageName(),
                                nativeAd.getPackageName(), "", nativeAd.getPromoteUrl()
                                , nativeAd.getStyle());
                    }

                }
            }
        };
        HttpUtils.addPostRequest(URIContant.GAME_DOWN, new TypeToken<DataBean<NativeAd>>() {
        }.getType(), mPageName, parms, httpListener);
    }

}
